document.addEventListener('DOMContentLoaded', function() {
  const tabList = document.getElementById('tabList');
  const copyButton = document.getElementById('copyButton');
  const statusDiv = document.getElementById('status');
  const searchInput = document.getElementById('searchInput');
  const noResults = document.getElementById('noResults');
  
  let allTabs = []; // 存储所有标签页

  // 获取所有打开的标签页
  function loadTabs() {
    chrome.tabs.query({ currentWindow: true }, function(tabs) {
      allTabs = tabs;
      updateTabList(tabs);
    });
  }

  // 初始加载
  loadTabs();

  // 监听标签页变化
  chrome.tabs.onCreated.addListener((tab) => {
    // 只有当新标签页在当前窗口时才重新加载
    if (tab.windowId === chrome.windows.WINDOW_ID_CURRENT) {
      loadTabs();
    }
  });

  chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
    // 只有当关闭的标签页在当前窗口时才重新加载
    if (removeInfo.windowId === chrome.windows.WINDOW_ID_CURRENT) {
      loadTabs();
    }
  });

  chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    // 只有当更新的标签页在当前窗口时才重新加载
    if (tab.windowId === chrome.windows.WINDOW_ID_CURRENT && (changeInfo.title || changeInfo.url)) {
      loadTabs();
    }
  });

  // 搜索功能
  searchInput.addEventListener('input', function(e) {
    const searchText = e.target.value.toLowerCase();
    const filteredTabs = allTabs.filter(tab => 
      tab.title.toLowerCase().includes(searchText) || 
      tab.url.toLowerCase().includes(searchText)
    );
    updateTabList(filteredTabs);
  });

  // 更新标签页列表
  function updateTabList(tabs) {
    // 保存当前选中的值
    const currentSelected = tabList.value;
    
    tabList.innerHTML = '<option value="" disabled>选择源标签页</option>';
    
    if (tabs.length === 0) {
      noResults.style.display = 'block';
      return;
    }
    
    noResults.style.display = 'none';

    // 获取当前活动标签页
    chrome.tabs.query({ active: true, currentWindow: true }, function(activeTabs) {
      if (activeTabs.length === 0) return;
      
      const activeTab = activeTabs[0];

      // 直接按照标签页索引排序
      const sortedTabs = [...tabs].sort((a, b) => a.index - b.index);

      // 记录当前活动标签页的选项位置
      let activeOptionIndex = -1;
      
      sortedTabs.forEach((tab, index) => {
        const option = document.createElement('option');
        option.value = tab.id;
        
        // 标记当前活动标签页
        const isActiveTab = tab.id === activeTab.id;
        if (isActiveTab) {
          activeOptionIndex = index;
          option.selected = true; // 默认选中当前标签页
        }
        
        const tabTitle = `${tab.index + 1}. ${tab.title}${isActiveTab ? ' (当前页面)' : ''}`;
        
        option.textContent = tabTitle;
        option.title = tab.url;
        
        // 为当前活动标签页添加特殊样式
        if (isActiveTab) {
          option.style.fontWeight = 'bold';
          option.style.backgroundColor = '#f0f7ff';
        }
        
        tabList.appendChild(option);
      });

      // 确保当前标签页可见
      if (activeOptionIndex !== -1) {
        // 等待DOM更新完成
        setTimeout(() => {
          const select = tabList;
          const options = select.options;
          const optionHeight = select.offsetHeight / select.size;
          
          // 计算最佳滚动位置
          const targetPosition = (activeOptionIndex + 1) * optionHeight; // +1 因为有提示选项
          const selectHeight = select.offsetHeight;
          const scrollPosition = targetPosition - (selectHeight / 2);
          
          select.scrollTop = Math.max(0, scrollPosition);
        }, 0);
      }
    });
  }

  copyButton.addEventListener('click', async function() {
    if (!tabList.value) {
      showStatus('请先选择源标签页', 'error');
      return;
    }

    copyButton.disabled = true;
    copyButton.textContent = '复制中...';
    
    try {
      const selectedTabId = parseInt(tabList.value);
      const selectedTab = await chrome.tabs.get(selectedTabId);
      
      if (!selectedTab) {
        throw new Error('所选标签页已关闭');
      }

      const cookies = await chrome.cookies.getAll({
        url: selectedTab.url
      });

      if (cookies.length === 0) {
        throw new Error('未找到任何Cookie');
      }

      const [currentTab] = await chrome.tabs.query({ active: true, currentWindow: true });
      const currentUrl = new URL(currentTab.url);
      
      let successCount = 0;
      let failCount = 0;

      for (const cookie of cookies) {
        try {
          // 先删除同名的旧cookie
          await chrome.cookies.remove({
            url: currentTab.url,
            name: cookie.name
          });

          // 构建新的cookie数据
          const cookieData = {
            url: currentTab.url,
            name: cookie.name,
            value: cookie.value,
            domain: currentUrl.hostname,
            path: cookie.path || '/',
            secure: currentUrl.protocol === 'https:' ? cookie.secure : false,
            httpOnly: cookie.httpOnly,
            sameSite: cookie.sameSite || 'Lax',
            storeId: cookie.storeId
          };

          // 如果有过期时间，添加到cookie数据中
          if (cookie.expirationDate) {
            cookieData.expirationDate = cookie.expirationDate;
          }

          // 设置新cookie
          await chrome.cookies.set(cookieData);
          console.log(`成功设置cookie: ${cookie.name}`, cookieData);
          successCount++;
        } catch (error) {
          console.error(`设置cookie失败: ${cookie.name}`, error);
          console.log('Cookie详情:', {
            name: cookie.name,
            value: cookie.value,
            domain: cookie.domain,
            path: cookie.path,
            secure: cookie.secure,
            httpOnly: cookie.httpOnly,
            sameSite: cookie.sameSite,
            expirationDate: cookie.expirationDate
          });
          failCount++;
        }
      }

      if (successCount > 0) {
        showStatus(
          `复制完成！成功: ${successCount} 失败: ${failCount}`,
          failCount === 0 ? 'success' : 'error'
        );
      } else {
        throw new Error(`尝试复制 ${cookies.length} 个Cookie全部失败`);
      }
    } catch (error) {
      console.error('复制过程中发生错误:', error);
      showStatus('复制过程中发生错误: ' + error.message, 'error');
    } finally {
      copyButton.disabled = false;
      copyButton.textContent = '复制Cookie到当前页面';
    }
  });

  function showStatus(message, type) {
    statusDiv.textContent = message;
    statusDiv.className = 'status ' + type;
  }
}); 